import { Injectable } from "@angular/core";
import {
  HttpEvent,
  HttpRequest,
  HttpHandler,
  HttpInterceptor
} from "@angular/common/http";
import { Observable } from "rxjs";
import { LocalStorageService } from '../service/localStorageService/local-storage.service';
import { Router } from '@angular/router';
import { serverPath } from '../urlConfig';

// 发送请求前拦截
@Injectable()
export class RequestInterceptor implements HttpInterceptor {
  constructor(public localStorage: LocalStorageService, public router: Router) {

  }
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    console.log("发送请求前拦截");

    const token = this.localStorage.getItem('token');

    // 拦截get请求 携带accessToken
    if (req.method === 'GET') {
      const authReq = req.clone({
        url: req.url.concat('?accessToken=', token.accessToken),// 传递访问令牌
      })
      return next.handle(authReq);

    } 
    // else if (req.method === 'POST') {
    //   if (req.url !== `${serverPath}signIn` && req.url !== `${serverPath}opus/file`) {

    //     const newbody: object = {
    //       accessToken: token.accessToken,
    //       refreshToken: token.refreshToken
    //     }
    //     const authReq = req.clone({
    //       body: newbody

    //     })
    //     return next.handle(authReq);
    //   }

    // }


    // 一开始进入登录界面时本地是没有存储token的
    if (req.url !== "https://node.cx-tidc.com/login") {
      if (token === null) {
        this.router.navigate(['/login'])
      }
    }

    // 当点击登录时，会抛出此错误  You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
    // 只需加入以下代码即可解决
    if (req.headers.get('Authorization') == null) {
      return next.handle(req);
    } else {
      return next.handle(req);
    }

  }

}
